<template>
    <div class="addProductInfo">
        <el-card shadow="never" style="width:100% ; border:none">
            <div slot="header">
                <span class="search-title">基本信息</span>
            </div>
            <el-form :model="baseInfoForm" :rules="rules" ref="ruleForm" label-width="100px">
                <el-form-item label="商品分类" prop="cates">
                    <el-cascader
                        class="normal-input"
                        v-model="baseInfoForm.cates"
                        :options="categoryList"
                        :props="{ multiple: true, emitPath: false }"
                        clearable
                    ></el-cascader>
                </el-form-item>
                <el-form-item label="商品名称" prop="name">
                    <el-input
                        v-model="baseInfoForm.name"
                        maxlength="30"
                        show-word-limit
                        class="normal-input"
                    ></el-input>
                </el-form-item>
                <el-form-item label="商品编码" prop="code">
                    <el-input v-model="baseInfoForm.code" class="normal-input"></el-input>
                </el-form-item>
                <el-form-item label="商品描述" prop="description">
                    <el-input
                        v-model="baseInfoForm.description"
                        maxlength="16"
                        show-word-limit
                        class="normal-input"
                    ></el-input>
                </el-form-item>
                <el-form-item label="商品展示图" prop="imageUrls">
                    <el-row>
                        <el-col
                            v-for="(imgUrl, index) in baseInfoForm.imageUrls"
                            :key="index"
                            class="img-urls"
                        >
                            <span class="coverImg">
                                <i class="el-icon-close deleteImg" @click="deleteImg(imgUrl)" />
                            </span>
                            <el-image
                                :src="imgUrl"
                                fit="fill"
                                class="image-slot"
                                style="width: 180px; height: 180px;"
                            >
                                <div slot="error" class="image-slot">
                                    <i
                                        class="el-icon-picture-outline"
                                        style="width: 100%; height: 100%"
                                    ></i>
                                </div>
                            </el-image>
                        </el-col>
                        <div class="img-add">
                            <div class="img-uploader">
                                <i
                                    class="el-icon-plus img-uploader-icon"
                                    @click="showPictureSelect(1)"
                                ></i>
                            </div>
                            <span class="form-advice">建议尺寸800*400PX</span>
                            <!-- </el-upload> -->
                        </div>
                    </el-row>
                </el-form-item>
                <el-form :rules="rules">
                    <el-row style="width:1200px">
                        <el-col :span="10">
                            <el-form-item label="首页活动图" prop="coverUrl">
                                <div
                                    class="avatar-uploader"
                                    style="width:320px; display:inline-block; vertical-align:top"
                                >
                                    <div class="avatar-uploader">
                                        <img
                                            v-if="baseInfoForm.coverUrl"
                                            :src="baseInfoForm.coverUrl"
                                            class="avatar"
                                            @click="showPictureSelect(2)"
                                        />
                                        <i
                                            v-else
                                            class="el-icon-plus avatar-uploader-icon"
                                            @click="showPictureSelect(2)"
                                        ></i>
                                    </div>

                                    <!-- </el-upload> -->
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item label="商品视频" prop="videoUrl">
                                <el-row type="flex">
                                    <div
                                        class="avatar-uploader"
                                        style="width:320px; display:inline-block; vertical-align:top"
                                    >
                                        <div class="avatar-uploader">
                                            <video
                                                v-if="baseInfoForm.videoUrl"
                                                :src="baseInfoForm.videoUrl"
                                                class="avatar"
                                                controls="controls"
                                                @click="showPictureSelect(3)"
                                            ></video>
                                            <i
                                                v-else
                                                class="el-icon-plus avatar-uploader-icon"
                                                @click="showPictureSelect(3)"
                                            ></i>
                                        </div>

                                        <!-- </el-upload> -->
                                    </div>
                                    <span class="form-advice advice-vedio">建议比例16：9</span>
                                </el-row>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <el-form-item label="角标" prop="cornerMarker">
                    <el-radio-group v-model="baseInfoForm.cornerMarkId">
                        <el-row type="flex" :gutter="30">
                            <el-col v-for="item in cornerMarkerUrlList" :key="item.id">
                                <el-image
                                    style="font-size:50px"
                                    :src="item.url"
                                    fit="fill"
                                    class="image-slot"
                                >
                                    <div slot="error" class="image-slot">
                                        <i
                                            class="el-icon-picture-outline"
                                            style="font-size:180px"
                                        ></i>
                                    </div>
                                </el-image>
                                <el-radio
                                    :label="item.id"
                                    style="margin-top:10px"
                                    @click.native.prevent="callbackChange(item.id)"
                                >
                                    <div style="width:0px"></div>
                                </el-radio>
                            </el-col>
                        </el-row>
                    </el-radio-group>
                </el-form-item>
                <!-- <el-form-item label="预设点击数" prop="hitCount">
                    <el-row class="number-input">
                        <el-input v-model="baseInfoForm.hitCount" type="number">
                            <span slot="append">次</span>
                        </el-input>
                    </el-row>
                </el-form-item> -->
                <el-form-item label="售后规则" prop="maxRefundDay">
                    <el-row>
                        <el-input
                            v-model="baseInfoForm.maxRefundDay"
                            type="number"
                            class="number-input"
                        >
                            <span slot="append">天</span>
                        </el-input>
                        <span>1则表示收货当天可退货，2则表示收货日第二日可退货</span>
                    </el-row>
                </el-form-item>
                <el-form-item>
                    <el-input
                        style="width:800px"
                        v-model="baseInfoForm.postSaleDescription"
                        placeholder="售后补充说明"
                    ></el-input>
                </el-form-item>
            </el-form>
            <!-- </el-main> -->
        </el-card>
        <!-- </el-container> -->

        <div v-if="showSelectPicture">
            <el-dialog title="选择图片" :visible.sync="showSelectPicture" width="900px">
                <select-picture
                    @select="handleConfirmSelectPicture"
                    @close="handleCloseSelectPicture"
                ></select-picture>
            </el-dialog>
        </div>
    </div>
</template>
<script>
// 临时数据

var tempVideoUrl = 'http://qnimg.starliu.cn/%E7%BC%96%E8%AF%91%E5%8E%9F%E7%90%86-1.mp4';
//var tempImgUrl = "http://qnimg.starliu.cn/tt.jpeg";
var tempImgUrl = '';
import SelectPicture from '@/components/ImageGroup/selectPicture';
import { getCateList, checkGoodName } from '@/api/goodsBase';
import { getCortList } from '@/api/cornerMark';
import { validatInteger } from '@/utils/validate.js';
import { mapGetters } from 'vuex';
export default {
    name: 'baseInfo',
    mounted() {
        this.init();
        // 此阶段props值不一定能取到，使用路由判断
        if (this.$route.path.indexOf('updateProduct') > -1) {
            //   console.log(this.goodsDetailInfo);
            this.opmode = 1;
        } else {
            this.opmode = 0;
        }
    },
    components: { SelectPicture },
    computed: {
        ...mapGetters(['goodsDetailInfo'])
    },
    props: {
        id: ''
    },
    watch: {
        goodsDetailInfo: function() {
            if (
                this.goodsDetailInfo &&
                this.goodsDetailInfo.cates &&
                this.goodsDetailInfo.resourceList
            ) {
                this.baseInfoForm = {
                    ...this.baseInfoForm,
                    ...this.goodsDetailInfo.goods,
                    cates: this.goodsDetailInfo.cates.map(el =>
                        JSON.stringify({ id: el.id, name: el.name, parentId: el.parentId })
                    ),
                    imageUrls: this.goodsDetailInfo.resourceList.map(el => el.resourceUrl)
                };
                this.initailName = this.baseInfoForm.name;
            }
        }
    },
    porps: {
        mode: 1
    },
    data() {
        var validateimageUrls = (rule, value, callback) => {
            if (this.validateimageUrls && this.validateimageUrls.length == 0) {
                return callback(new Error('请上传商品展示图'));
            } else {
                callback();
            }
        };
        var validatDay = (rule, value, callback) => {
            if (value && !validatInteger(value.toString())) {
                return callback(new Error('请输入大于等于0的整数'));
            } else {
                callback();
            }
        };

        var validatDayOverOne = (rule, value, callback) => {
            if (value && !validatInteger(value.toString()) && value < 1) {
                return callback(new Error('请输入大于等于1的整数'));
            } else {
                callback();
            }
        };

        var validateNameExist = (rule, value, callback) => {
            let id = this.id ? this.id : null;
            if ((this.opmode = 1 && value == this.initailName)) {
                // 修改模式
                callback();
            }
            checkGoodName({ name: value, id })
                .then(res => {
                    if (res.data.success == true && res.data.data == true) {
                        return callback(new Error('商品名称已存在'));
                    } else {
                        callback();
                    }
                })
                .catch(err => {
                    callback();
                });
        };
        return {
            opmode: 0,
            categoryList: [],
            baseInfoForm: {
                cates: [],
                cornerMarkId: '270734256106508300',
                coverUrl: '', //首页展示图连接
                description: '', // 商品描述
                goodsAttr: {},
                imageUrls: [], //商品展示图
                maxRefundDay: 1,
                name: '',
                postSaleDescription: '',
                // preHitCount: 0,
                videoUrl: '', // 视频连接
                //  hitCount: 0,
                description: '',
                conerMarker: 1
            },
            dialogImageUrl: '',
            dialogVisible: false,
            cornerMarkerUrlList: [],
            showSelectPicture: false,
            initailName: '',

            rules: {
                cates: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
                name: [
                    { required: true, message: '请输入商品名称', trigger: 'change' },
                    {
                        validator: validateNameExist,
                        trigger: 'blur'
                    }
                ],
                imageUrls: [
                    { required: true, message: '请上传商品展示图', trigger: 'change' },
                    { validator: validateimageUrls, trigger: 'change' }
                ],
                coverUrl: [{ required: true, message: '请上传首页展示图', trigger: 'change' }],
                maxRefundDay: [
                    { required: true, message: '请填写内容', trigger: 'change' },
                    { validator: validatDayOverOne, trigger: 'change' }
                ]
            }
        };
    },
    methods: {
        init() {
            getCateList().then(res => {
                if (res.data && res.data.success == true) {
                    let list = res.data.data;
                    this.categoryList = list.map(el => {
                        let option = {
                            value: JSON.stringify({
                                id: el.category.id,
                                name: el.category.name,
                                parentId: el.category.parentId
                            }),
                            label: el.category.name,
                            children: el.detailList.map(el => {
                                return {
                                    value: JSON.stringify({
                                        id: el.categoryId,
                                        name: el.name,
                                        parentId: el.parentId
                                    }),
                                    label: el.name
                                };
                            })
                        };
                        if (!option.children || option.children.length == 0) {
                            option['disabled'] = true;
                        }
                        return option;
                    });
                } else {
                    this.categoryList = [];
                }
            });

            getCortList().then(res => {
                if (res.data.success === true) {
                    //console.log(`- cort: `, res.data.data);
                    this.cornerMarkerUrlList = res.data.data;
                    // console.log('cornerList', this.cornerMarkerUrlList);
                } else {
                }
            });
        },
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    alert('submit!');
                } else {
                    // console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        handleRemove(file, fileList) {
            // console.log(file, fileList);
        },
        handlePictureCardPreview(file) {
            console.log('previewFIle', file.url);
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        handleAvatarSuccess(res, file) {
            this.ActivityImg = file.url;
        },
        handleVideoSuccess(res, file) {},
        beforeVideoUpload(file) {},
        validateForm() {
            return this.$refs['ruleForm'].validate();
        },

        showPictureSelect(option) {
            this.pictureOption = option;
            this.showSelectPicture = true;
        },
        handleConfirmSelectPicture(imageUrl) {
            if (this.pictureOption === 1) {
                if (
                    this.baseInfoForm.imageUrls &&
                    this.baseInfoForm.imageUrls.indexOf(imageUrl) > -1
                ) {
                    this.$message('请勿重复添加');
                    return;
                }
                this.baseInfoForm.imageUrls.push(imageUrl);
            } else if (this.pictureOption === 2) {
                this.baseInfoForm.coverUrl = imageUrl;
            } else if (this.pictureOption == 3) {
                this.baseInfoForm.videoUrl = imageUrl;
            }
            this.showSelectPicture = false;
        },
        handleCloseSelectPicture() {
            this.showSelectPicture = false;
        },
        deleteImg(imgUrl) {
            this.baseInfoForm.imageUrls = this.baseInfoForm.imageUrls.filter(el => el !== imgUrl);
        },
        callbackChange(el) {
            el == this.baseInfoForm.cornerMarkId
                ? (this.baseInfoForm.cornerMarkId = '')
                : (this.baseInfoForm.cornerMarkId = el);
        }
    }
};
</script>

<style scoped>
.search-title {
    font-size: 18px;
    font-weight: bold;
}
.form-container {
    padding: 0px;
}
.form-advice {
    color: #999999;
}
.number-input {
    width: 200px;
}
.normal-input {
    width: 400px;
}
.addition-input {
    margin-top: 15px;
}
.image-slot {
    width: 50px;
    height: 50px;
}
.img-add {
    width: 180px;
    display: inline-block;
    vertical-align: top;
    margin-top: 10px;
}
</style>

<style lang="scss">
.addProductInfo {
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .img-uploader {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        box-sizing: inherit;
        display: inline-block;
        // position: relative;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409eff;
    }
    .avatar-uploader-icon {
        cursor: pointer;
        border: 1px dashed #d9d9d9;
        font-size: 28px;
        color: #8c939d;
        width: 320px;
        height: 180px;
        line-height: 180px;
        text-align: center;
    }

    .img-uploader-icon {
        font-size: 28px;
        cursor: pointer;
        color: #8c939d;
        width: 180px;
        height: 180px;
        line-height: 180px;
        text-align: center;
    }
    .el-radio:focus:not(.is-focus):not(:active):not(.is-disabled) .el-radio__inner {
        -webkit-box-shadow: 0 0 2px 2px #0000;
        box-shadow: 0 0 2px 2px #0000;
    }
    .avatar {
        width: 320px;
        height: 180px;
        display: block;
        cursor: pointer;
    }
    .advice-vedio {
        margin-left: 15px;
        line-height: 180px;
        text-align: center;
        cursor: pointer;
    }
    .el-radio__label {
        display: none;
    }
    .el-radio {
        display: flex;
        justify-content: center;
    }
    .coverImg {
        position: absolute;
        width: 100%;
        height: 100%;
        left: 0;
        top: 0;
        cursor: default;
        text-align: center;
        color: #fff;
        opacity: 0;
        font-size: 20px;
        background-color: rgba(0, 0, 0, 0.3);
        transition: opacity 0.3s;
        z-index: 100;
    }
    .coverImg:hover {
        z-index: 100;
        opacity: 1;
    }
    .deleteImg {
        float: right;
        margin-right: 2px;
        margin-top: 3px;
        cursor: pointer;
    }
    .img-urls {
        width: 180px;
        height: 180px;
        margin-right: 10px;
        margin-top: 10px;
        display: inline-block;
        position: relative;
    }
}
</style>
